<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="签订日期">
                <a-range-picker
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始日期','结束日期']"
                  v-model="queryParam.signDate" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="交付日期">
                <a-range-picker
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始日期','结束日期']"
                  v-model="queryParam.deliveryDate" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="合同名称">
                <a-input
                  v-model="queryParam.contractName"
                  placeholder="请输入合同名称" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="合同类型">
                <a-select
                  v-model="queryParam.contractType"
                  placeholder="请选择">
                  <a-select-option :value="1">项目合同</a-select-option>
                  <a-select-option :value="2">采购合同</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="甲方">
                <a-input
                  v-model="queryParam.firstParty"
                  placeholder="请输入甲方" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <a-form-item label="乙方">
                <a-input
                  v-model="queryParam.secondParty"
                  placeholder="请输入乙方" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="10">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {}; this.$refs.table.refresh()}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="handleAdd">新建</a-button>
      </div>
      <div>
        <s-table
          ref="table"
          size="default"
          rowKey="contractId"
          :columns="columns"
          :data="loadData"
          :customRow="tableCustomRow"
          showPagination="auto">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <!-- <a @click="handleEdit(record)">配置</a>
              <a-divider type="vertical" /> -->
              <a
                @click="showDetail(record)"
                v-if="detail">详情</a>
              <a-divider type="vertical" />
              <a
                v-if="deleteBtn"
                @click="handleDelete(record)"
              >删除</a>
            </template>
          </span>
          <span
            slot="signDate"
            slot-scope="text, record">
            {{ record.signDate.split(' ')[0] }}
          </span>
          <span
            slot="deliveryDate"
            slot-scope="text, record">
            {{ record.deliveryDate.split(' ')[0] }}
          </span>
        </s-table>
      </div>
      <create-form
        ref="createModal"
        :isEdit="isEdit"
        :suppliers="suppliers"
        :customers="customers"
        :visible="visible"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { getContractList, saveContract, supplierSelect, getAllCustom, getFileByIds, updateContract, deleteContract } from '@/api/manage'
import CreateForm from './modules/CreateForm'
import FileCreateForm from './modules/FileCreateForm'
import { message, Modal } from 'ant-design-vue'
import { fileColumns } from './config'
import { mapGetters } from 'vuex'
import { isInMenu } from '../config'
// import { supplierSelect } from "module";
const columns = [
  {
    title: '#',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '合同名称',
    dataIndex: 'contractName'
  },
  {
    title: '合同类型',
    dataIndex: 'contractTypeName'
  },
  {
    title: '甲方',
    dataIndex: 'firstParty'
  },
  {
    title: '乙方',
    dataIndex: 'secondParty'
  },
  {
    title: '合同金额',
    dataIndex: 'money'
  },
  {
    title: '签订日期',
    dataIndex: 'signDate',
    scopedSlots: { customRender: 'signDate' }
  },
  {
    title: '交付日期',
    dataIndex: 'deliveryDate',
    scopedSlots: { customRender: 'deliveryDate' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    STable,
    CreateForm,
    FileCreateForm
  },
  data () {
    this.columns = columns
    this.fileColumns = fileColumns
    return {
      //
      suppliers: [],
      customers: [],
      // 权限参数
      detail: false, // 详情
      list: false, // 查
      save: false, // 删
      deleteBtn: false, // 删
      update: false,
      // create model
      visible: false,
      confirmLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      fileTabLoading: false,
      fileCreateVisible: false,
      files: undefined,
      isAdd: false,
      isEdit: false,
      conRecord: undefined,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        if (this.queryParam.signDate) {
          param.signBeginDate = this.queryParam.signDate[0]
          param.signEndDate = this.queryParam.signDate[1]
        }
        if (this.queryParam.deliveryDate) {
          param.deliveryBeginDate = this.queryParam.deliveryDate[0]
          param.deliveryEndDate = this.queryParam.deliveryDate[1]
        }
        return this.list && getContractList(
          Object.assign({}, param, requestParameters, { signDate: undefined, deliveryDate: undefined })
        ).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      },
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null
    }
  },
  filters: {},
  created () {
    this.list = isInMenu(this.menu, 'ROLE_but:contract:list')
    this.save = isInMenu(this.menu, 'ROLE_but:contract:save')
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:contract:delete')
    this.update = isInMenu(this.menu, 'ROLE_but:contract:update')
    this.detail = isInMenu(this.menu, 'ROLE_but:contract:info')
  },
  mounted () {
    supplierSelect({}).then(res => { this.suppliers = res.data })
    getAllCustom({}).then(res => { this.customers = res.data })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    showDetail (record) {
      this.$router.push({
        name: 'contractInfo',
        path: '/contract/contractInfo',
        query: {
          contractId: record.contractId
        }
      })
    },
    handleDelete (record) {
      Modal.confirm({
        title: '删除合同',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          deleteContract({ contractId: record.contractId }).then(() => {
            this.$refs.table.refresh()
            this.files = undefined
            message.success('删除成功')
          })
        }
      })
    },
    handleAdd () {
      this.visible = true
      this.isAdd = true
      this.isEdit = false
    },
    getFiles (record) {
      this.fileTabLoading = true
      getFileByIds({ fileIds: record.fileIds })
        .then(res => {
          this.files = res.data
        })
        .finally(() => {
          this.fileTabLoading = false
        })
    },
    handleEdit (record) {
      this.isAdd = false
      this.isEdit = true
      this.visible = true
      const form = this.$refs.createModal.form
      this.conRecord = record
      this.$nextTick(() => {
        form.setFieldsValue(record)
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.isAdd) {
            saveContract(values)
              .then(res => {
                this.$refs.table.refresh()
              })
              .finally(() => {
                this.visible = false
                this.$refs.createModal.resetFileList()
                this.confirmLoading = false
                form.resetFields()
              })
          } else if (this.isEdit) {
            updateContract(
              Object.assign({}, values, {
                fileIds: this.conRecord.fileIds,
                contractId: this.conRecord.contractId,
                signDate: this.conRecord.signDate.split(' ')[0],
                deliveryDate: this.conRecord.deliveryDate.split(' ')[0]
              })
            )
              .then(res => {
                this.$refs.table.refresh()
              })
              .finally(() => {
                this.visible = false
                this.$refs.createModal.resetFileList()
                form.resetFields()
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.contractId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.contractId
            this.conRecord = record
            this.physicalSurveyCurrRowId = record.contractId
            record.fileIds ? this.getFiles(record) : (this.files = [])
          }
        }
      }
    }
  }
}
</script>
